package com.jiazhong.mingxing.project.bookstore.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.mingxing.project.bookstore.commons.bean.User;
import com.jiazhong.mingxing.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.UserMapper;
import com.jiazhong.mingxing.project.bookstore.commons.util.JsonResult;
import com.jiazhong.mingxing.project.bookstore.commons.util.MD5Util;
import com.jiazhong.mingxing.project.bookstore.commons.util.ResultTool;
import com.jiazhong.mingxing.project.bookstore.front.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final String FRONT_TOKEN = "front_token:";

    @Override
    public JsonResult login(User user) {
        // 1. 校验账号是否正确
        User one = checkUsername(user.getUsername());
        // 2. 如果错误
        if (one == null) {
            return ResultTool.fail("账号不存在", 401);
        }
        // 3. 如果正确，判断密码是否正确
        String inputPassword = MD5Util.encryptMD5(user.getPassword()); // 用户输入的
        String sqlPassword = one.getPassword(); // 数据库中的
        // 4. 密码不一致
        if (!Objects.equals(inputPassword, sqlPassword)) {
            return ResultTool.fail("密码错误", 401);
        }
        // 5. 如果密码正确 生成token
        String token = JwtConfig.getJwtToken(one);
        // 6. 保存
        stringRedisTemplate.opsForValue().set(FRONT_TOKEN + one.getId(), token, 1, TimeUnit.DAYS);
        // 7. 返回token
        return ResultTool.success(token);
    }

    private User checkUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }

}
